import React, { useEffect, useState } from 'react'
import { useCallbackOne } from 'use-memo-one'

import { TopContainer, TitleImg, TitleImg1, TitleImg2, TitleImg3, Container, ContainerTopRadius, ContainerTopRadius2, Content } from './styled'

import GoDownload from './views/goDownload/'
import ContentView from './views/contentView/'
import InputCode from './views/inputCode/'
import Tips from './views/Tips/'
import { getPhoneType } from '@/untils'

export default () => {
    var _shareInstallData = window.ShareInstall.parseUrlParams()
    var Phone = getPhoneType() === 'ios' ? '苹果' : '安卓';
    var wakeupOrInstall = null

    const [shareInstallData, setShareInstallData] = useState(_shareInstallData)
    const [invitecode, setInvitecode] = useState('')
    const [hasShareInstallData, setHasShareInstallData] = useState(false)
    useEffect(() => {
        window.TDAPP.onEvent("H5-" + Phone + '-访问');
    }, [Phone])
    useEffect(() => {
        try { setInvitecode(shareInstallData?.cardno) }
        catch{ return void 0 }
    }, [shareInstallData])

    useEffect(() => {
        if (!invitecode) return

        var _invitecode = invitecode.replace(/' '/g, '')
        var _hasShareInstallData = _invitecode.length >= 6

        setHasShareInstallData(_hasShareInstallData)
    }, [invitecode])

    useEffect(() => {
        if (!hasShareInstallData) {
            var div = document.body;
            document.body.scrollTop = div.scrollHeight;
            return;
        }
        document.body.style.marginTop='-29px';
        document.body.scrollTop='20';
        new window.ShareInstall({
            appKey: 'AEBK6FEBFKFBAA',
            // 可选项，微信中打开自定义遮罩层
            shadow: () => "<div id='shareinstall_shadow' style='position:fixed;left:0;top:0;background:rgba(0,255,0,0.5);filter:alpha(opacity=50);width:100%;height:100%;z-index:10000;'/>",
            onready: function () {
                wakeupOrInstall = this.wakeupOrInstall
            }
        }, shareInstallData)

    }, [hasShareInstallData])
    function Down() {
        void wakeupOrInstall?.()
        window.TDAPP.onEvent("H5-" + Phone + '-下载')
    }
    return <>
        <TopContainer>
                <TitleImg1 />
                <TitleImg2 />
                <TitleImg />
                <TitleImg3 />
            </TopContainer>
            <Tips />
            <Container>
                {hasShareInstallData ? <ContainerTopRadius>
                    <GoDownload {...{ invitecode }} wakeupOrInstall={() => Down()} />
                </ContainerTopRadius> : <ContainerTopRadius2>
                        <InputCode setShareInstallData={setShareInstallData} />
                    </ContainerTopRadius2>}
                <Content>
                    {hasShareInstallData && <ContentView wakeupOrInstall={() => Down()} />}
                </Content>
            </Container>

    </>
}
